package cn.xspace.app.filemg.fragment;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListView;
import android.widget.Toast;

import com.xspace.android.xafcommon.util.BaseRProxy;
import com.xspace.android.xafcommon.util.DateUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;

import cn.xspace.app.filemg.bean.ChooseFileInfo;
import cn.xspace.app.filemg.bean.FileInfo;
import cn.xspace.app.filemg.bean.ImgPackInfo;
import cn.xspace.app.filemg.util.CallBack;
import cn.xspace.app.filemg.view.FileVoidAdapter;

public class FileMusicFragment extends Fragment implements CallBack {
    private Context mContext;
    private ArrayList<ImgPackInfo> packList = new ArrayList<ImgPackInfo>();
    private FileVoidAdapter mAdapter;
    private ExpandableListView mListView;
    private boolean checkFlag, imgCheckFlag;
    private static CallBack mCallBack;
    private boolean isOver = true;
    private boolean isUpdate = true;
    private ArrayList<FileInfo> imgList;
    private boolean isOpen = true;
    private MyAsyncTask mMyAsyncTask;
    private ImgPackInfo packInfo;
    private HashMap<String, ArrayList<FileInfo>> mGruopMap = new HashMap<String, ArrayList<FileInfo>>();
    private ChooseFileInfo chooseInfo = new ChooseFileInfo();

    public static FileMusicFragment newInstance(CallBack callBack) {
        FileMusicFragment newFragment = new FileMusicFragment();
        mCallBack = callBack;
        return newFragment;

    }

    public void queryOver() {
        isOver = true;
        handler.sendEmptyMessage(1);
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    if (mAdapter != null) {
                        try {
                            mAdapter.notifyDataSetChanged();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {
                        mAdapter = new FileVoidAdapter(mContext, packList,
                                FileMusicFragment.this);
                        mListView.setAdapter(mAdapter);
                    }
                    break;
                case 1:
                    if (mListView != null)
                        mListView.expandGroup(0);
                    break;

                default:
                    break;
            }
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = FileMusicFragment.this.getActivity();

    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        handler.removeMessages(0);
        handler.removeMessages(1);
        super.onDestroy();
    }

    private class MyAsyncTask extends AsyncTask {
        @Override
        protected Object doInBackground(Object... arg0) {
            queryMusic();
            queryVoid();
            // 通知Handler扫描音频完成
            handler.sendEmptyMessage(0);
            handler.sendEmptyMessage(1);
            return null;
        }

    }

    private void queryMusic() {
        String[] projection = {MediaStore.Audio.Media._ID,
                MediaStore.Audio.Media.DISPLAY_NAME,
                MediaStore.Audio.Media.DATA, MediaStore.Audio.Media.SIZE};
        String orderBy = MediaStore.Audio.Media.DISPLAY_NAME;
        Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        // getContentProvider(uri, projection, orderBy);
        //
        // Uri mImageUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
        ContentResolver mContentResolver = getActivity().getContentResolver();

        // 只查询音频
        Cursor mCursor = mContentResolver.query(uri, null, null, null, orderBy);
        ArrayList<FileInfo> testList = new ArrayList<FileInfo>();
        ImgPackInfo imgTest = null;
        imgTest = new ImgPackInfo();
        imgTest.setPackName("音频");
        imgTest.setImgList(testList);
        packList.add(imgTest);
        while (mCursor.moveToNext()) {
            // 获取音频的路径
            String path = mCursor.getString(mCursor
                    .getColumnIndex(MediaStore.Audio.Media.DATA));

            // 获取该音频的父路径名
            String parentName = new File(path).getParentFile().getName();

            FileInfo imgInfo = new FileInfo();
            imgInfo.setName(mCursor.getString(mCursor
                    .getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME)));
            imgInfo.setPath(path);
            imgInfo.setSize(mCursor.getLong(mCursor
                    .getColumnIndex(MediaStore.Audio.Media.SIZE)));
            if (imgInfo.getSize() * 100 / 1048576 <= 0) {
                continue;
            }
            imgInfo.setFileType("mp3");
            imgInfo.setPackageName(parentName);
            File tFile = new File(path);
            imgInfo.setTime(DateUtils.timeMillisToDateTimeString(
                    tFile.lastModified(), DateUtils.FORMAT_5));
            testList.add(imgInfo);

        }
        mCursor.close();
    }

    private void queryVoid() {
        String[] projection = {MediaStore.Video.Media._ID,
                MediaStore.Video.Media.DISPLAY_NAME,
                MediaStore.Video.Media.DATA, MediaStore.Video.Media.SIZE};
        String orderBy = MediaStore.Video.Media.DISPLAY_NAME;
        Uri uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
        // getContentProvider(uri, projection, orderBy);
        //
        // Uri mImageUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
        ContentResolver mContentResolver = getActivity().getContentResolver();

        // 只查询视频
        Cursor mCursor = mContentResolver.query(uri, null, null, null, orderBy);
        ArrayList<FileInfo> testList = new ArrayList<FileInfo>();
        ImgPackInfo imgTest = null;
        imgTest = new ImgPackInfo();
        while (mCursor.moveToNext()) {
            // 获取音频的路径
            String path = mCursor.getString(mCursor
                    .getColumnIndex(MediaStore.Video.Media.DATA));

            // 获取该音频的父路径名
            String parentName = new File(path).getParentFile().getName();

            FileInfo imgInfo = new FileInfo();
            imgInfo.setName(mCursor.getString(mCursor
                    .getColumnIndex(MediaStore.Video.Media.DISPLAY_NAME)));
            imgInfo.setPath(path);
            imgInfo.setFileType("mp4");
            imgInfo.setSize(mCursor.getLong(mCursor
                    .getColumnIndex(MediaStore.Video.Media.SIZE)));
            if (imgInfo.getSize() * 100 / 1048576 <= 0) {
                continue;
            }
            imgInfo.setPackageName(parentName);
            imgInfo.setTime(DateUtils.timeMillisToDateTimeString(mCursor
                            .getLong(mCursor
                                    .getColumnIndex(MediaStore.Video.Media.DATA)),
                    DateUtils.FORMAT_5));
            testList.add(imgInfo);

        }
        if (testList.size() > 0) {
            imgTest.setPackName("视频");
            imgTest.setImgList(testList);
            packList.add(imgTest);
        }
        mCursor.close();
    }

    public void initChooseData(ChooseFileInfo chooseInfo) {
        this.chooseInfo = chooseInfo;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(BaseRProxy.file_img, container, false);
        // mGridView = (GridView) view.findViewById(RProxy.gridview);
        mListView = (ExpandableListView) view
                .findViewById(BaseRProxy.favorite_webs_list_expandlv);
        if (packList.size() != 0) {
            mAdapter = new FileVoidAdapter(mContext, packList,
                    FileMusicFragment.this);
            mListView.setAdapter(mAdapter);
        } else {
            mMyAsyncTask = new MyAsyncTask();
            mMyAsyncTask.execute();
        }

        return view;

    }

    @Override
    public void checkedInfo(FileInfo info) {
        // TODO Auto-generated method stub
        info.setCheckFlag(!info.isCheckFlag());
        if (info.isCheckFlag()) {
            if (chooseInfo.getFileList().size() >= 10) {
                info.setCheckFlag(!info.isCheckFlag());
                Toast.makeText(getActivity(), "最多能选10个文件", Toast.LENGTH_SHORT)
                        .show();
            }
            if ((chooseInfo.getSize() + info.getSize()) > (1048576 * 100)) {
                info.setCheckFlag(!info.isCheckFlag());
                Toast.makeText(getActivity(), "所选文件已超过100MB",
                        Toast.LENGTH_SHORT).show();
            }
        }
        mAdapter.notifyDataSetChanged();
        mCallBack.checkedInfo(info);
    }
}
